// utils
import _throttle from 'lodash/throttle'
import { getAttrs, getListener } from '../utils'

const ROW_CLICK_EVENT = 'row-click'

export default {
  data() {
    return {
      // <row-click> 当前点击的行ID
      currentId: null
    }
  },
  methods: {
    // row-click event
    //
    // row-click 节流版本
    _throttleEmitRowClick: _throttle(
      function(row) {
        this.$emit(ROW_CLICK_EVENT, row)
      },
      3000,
      {
        trailing: false
      }
    ),
    // row-click 普通版本
    _emitRowClick(row) {
      this.$emit(ROW_CLICK_EVENT, row)
    },
    cellClick(...params) {
      const { row } = params[0]
      const rowId = getAttrs(this, 'row-id')
      const cellClickMethod = getListener(this, 'cell-click')
      const id = rowId ? row[rowId] : row._XID ? row._XID : row._X_ID

      if (id === this.currentId) {
        this._throttleEmitRowClick(row)
      } else {
        this._emitRowClick(row)
      }
      this.currentId = id
      if (cellClickMethod) {
        return cellClickMethod(...params)
      }
    },
    async editClosed(...params) {
      const customListener = getListener(this, 'editClosed')
      const _editConfig = getAttrs(this, 'editConfig')
      if (_editConfig?.trigger === 'single' && customListener) {
        this.singleEditLoading = true
        const res = await customListener(...params)
        this.singleEditLoading = false
        return res
      }
      return customListener?.(...params)
    }
  }
}
